import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPool {
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);
    private int maxPoolSize = 0;
    private List<Thread> threadslist = new ArrayList<>();

    public MyThreadPool(int corePoolSize, int maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
        for (int i = 0; i < corePoolSize; i++) {
            Thread t = new Thread(() -> {
                try {
                    while (true) {
                        Runnable runnable = queue.take();
                        runnable.run();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();
            threadslist.add(t);
        }
    }

    void submit(Runnable runnable) throws InterruptedException {
        //此处进行判定，判定当前任务队列的元素个数，是否比较长
        //如果队列元素比较长，说明已有的线程，不太能处理过来，创建新线程即可
        //如果队列不是很长，没必要创建新线程
        queue.put(runnable);
        if (queue.size() >= 500 && threadslist.size() < maxPoolSize) {
            //创建新的线程
            Thread t = new Thread(() -> {
                try {
                    while (true) {
                        Runnable task = queue.take();
                        task.run();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();
        }
    }
}

public class Demo2 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool threadPool = new MyThreadPool(10,10);

        for (int i = 0; i < 10000; i++) {
            int id = i;
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello " + id + "," + Thread.currentThread().getName());
                    // System.out.println("hello "+ i+ ","+Thread.currentThread().getName());
                    //i不能使用是因为线程捕获的问题
                }
            });
        }
    }
}
